import { api } from '@/services/api';
import type { UserDevice } from '@/services/generated/models';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm } from 'antd';
import React, { useRef } from 'react';
import { useAccess, useModel } from '@umijs/max';

const DeviceManage: React.FC = () => {
  const actionRef = useRef();
  const access = useAccess();
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  const columns: ProColumns<UserDevice>[] = [
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      search: false,
    },
    {
      title: '登录时间',
      dataIndex: 'lastLogin',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '最后活动时间',
      dataIndex: 'lastActivity',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '在线状态',
      dataIndex: 'isActive',
      valueType: 'select',
      valueEnum: {
        true: { text: '在线', status: 'Success' },
        false: { text: '离线', status: 'Default' },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => {
        if (record.isActive) {
          return (
            <Popconfirm
              title="确定要踢出该设备吗？"
              onConfirm={async () => {
                try {
                  await api.auth.authDevicesLogoutCreate({
                    id: record.deviceId,
                  });
                  message.success('设备已踢出');
                  actionRef.current?.reload();
                } catch (error) {
                  message.error('操作失败');
                }
              }}
            >
              <Button type="link" danger>
                踢出设备
              </Button>
            </Popconfirm>
          );
        }
        return null;
      },
    },
  ];

  return (
    <ProTable<UserDevice>
      headerTitle="我的设备"
      actionRef={actionRef}
      columns={columns}
      request={async () => {
        try {
          if (!currentUser?.id) {
            message.error('无法获取用户信息，请重新登录');
            return {
              data: [],
              success: false,
            };
          }
          const response = await api.auth.authDevicesList({
            userId: currentUser.id,
          });
          return {
            data: response,
            success: true,
          };
        } catch (error) {
          console.log('error', error);
          message.error('获取设备列表失败');
          return {
            data: [],
            success: false,
          };
        }
      }}
      rowKey="deviceId"
      search={false}
      toolBarRender={() => [
        <Button
          key="refresh"
          onClick={() => {
            actionRef.current?.reload();
          }}
        >
          刷新
        </Button>,
      ]}
    />
  );
};

export default DeviceManage;
